package com.cloud.poetry.base.aop;

import com.cloud.poetry.base.anno.DataSource;
import com.cloud.poetry.base.databases.DynamicDataSource;
import com.cloud.poetry.core.constant.DataSourceEnum;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author mengxj
 */
@Component
@Aspect
public class HandleDataSource implements Ordered {

    private Logger logger = LoggerFactory.getLogger(super.getClass());

    @Pointcut("@annotation(com.cloud.poetry.base.anno.DataSource)")
    private void cut(){
    }

    @Around("cut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object target = point.getTarget();
        Signature signature = point.getSignature();
        MethodSignature methodSignature = (MethodSignature)signature;
        Method method = target.getClass().getDeclaredMethod(methodSignature.getName(), methodSignature.getParameterTypes());
        DataSource datasource = method.getAnnotation(DataSource.class);
        DataSourceEnum ds = Objects.isNull(datasource) ? DataSourceEnum.FIRST : datasource.value();
        logger.info("current datasource is {}", ds);
        DynamicDataSource.setDataSource(ds);
        try {
            return point.proceed();
        }finally {
            DynamicDataSource.clearDataSource();
        }
    }

    @Override
    public int getOrder() {
        return 1;
    }
}